﻿/****************************************************************************
Copyright (c) 2014-2015 凌惊雪 微信:Lingjingxue 邮箱:lingjingxue@sina.com QQ:271487457

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

using ServerBase.Protocol;
using UtilPublic.ServerLoger;
using ServerBase.Service;
using System;
using System.Collections.Generic;
using ServerBase.Config;
using System.Diagnostics;
using System.Threading;
using UtilPublic.Serialization;
using UtilPublic.ApiDispatcher;
using ServerBase.LunarSocket;

namespace ServerBase.Service
{
    /// <summary>
    /// 消息分发器
    /// </summary>
    public static class BaseDispatch
    {
        //当前正在处理的协议ID
        public static EProtocolId ThisPId = EProtocolId.UNKNOWN_TYPE;
        public static LunarSession ThisSession = new LunarSession();
        public static LunarRequestInfo ThisReq;

        //绑定列表
        public static Dictionary<EProtocolId, Func<short>> DictProtocolEvent
            = new Dictionary<EProtocolId, Func<short>>();
        public static Dictionary<EProtocolId, Action<LunarSession, LunarRequestInfo>> DictProtocolEventImm
            = new Dictionary<EProtocolId, Action<LunarSession, LunarRequestInfo>>();

        //立即处理消息ID
        public static List<short> ListProtocolImm = new List<short>();

        
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        public static void DispatchApiRegister<T>(T t)
        {
            try
            {
                var dict = ApiDpProMgr.GetController(t);
                foreach (var kvp in dict)
                {
                    DictProtocolEvent[(EProtocolId)kvp.Key] = kvp.Value;
                }
            }
            catch (Exception ex)
            {
                loger.Error($"BaseDispatch DispatchApiRegister", ex);
            }
        }

        /// <summary>
        /// 绑定注册
        /// </summary>
        /// <param name="action"></param>
        /// <param name="id"></param>
        public static void BindEventHandler(Func<short> action, EProtocolId id)
        {
            if (DictProtocolEvent.ContainsKey(id))
            {
                loger.Warn($"重复注册消息 {id}");
            }
            DictProtocolEvent[id] = action;
            loger.Info($"注册消息 {id,-30} -> {(int)id,-10} -> {action.Method} 成功！");
        }
        /// <summary>
        /// 绑定注册（立即）
        /// </summary>
        /// <param name="action"></param>
        /// <param name="id"></param>
        public static void BindEventHandlerImm(Action<LunarSession, LunarRequestInfo> action, EProtocolId id)
        {
            if (DictProtocolEvent.ContainsKey(id))
            {
                loger.Warn($"重复注册消息 {id}");
            }
            ListProtocolImm.Add((short)id);
            DictProtocolEventImm[id] = action;
            loger.Info($"注册立即消息 {id,-30} -> {(int)id,-10} -> {action.Method} 成功！");
        }

        ///// <summary>
        ///// 新连接事件
        ///// </summary>
        ///// <param name="session"></param>
        //public static void OnAccept(IServer sender, IntPtr connId, IntPtr client)
        //{
        //    loger.Debug("接收到连接: " + connId);
        //}

        ///// <summary>
        ///// 有连接断开
        ///// </summary>
        ///// <param name="session"></param>
        ///// <param name="reason"></param>
        //public static void OnClose(IServer sender, IntPtr connId, SocketOperation socketOperation, int errorCode)
        //{
        //    loger.Debug("连接断开: " + connId);

        //}

        ///// <summary>
        ///// 消息分发
        ///// </summary>
        ///// <param name="session"></param>
        ///// <param name="requestInfo"></param>
        //public static void OnDispatch(TSender sender, IntPtr connId, LunarRequestInfo obj)
        //{
        //    if (requestInfo.ProtocolID == 0)
        //    {
        //        loger.Warn("收到空消息");
        //    }
        //    else if (ListProtocolImm.Contains(requestInfo.ProtocolID))
        //    {
        //        ProcessMessageImm(session, requestInfo);
        //    }
        //    else
        //    {
        //        session.ListReq.Enqueue(requestInfo);
        //    }
        //}

        //当前心跳处理消息数目
        public static int CountMsgs = 0;
        /// <summary>
        /// 分发器心跳
        /// </summary>
        public static void Loop()
        {
            CountMsgs = 0;
            foreach (var session in BaseAppServer.AllSessions.Values)
            {
                if (session != null)
                {
                    while (session.ListReq.TryDequeue(out var msg))
                    {
                        ProcessMessage(session, msg);
                        CountMsgs++;
                    }
                }
            }
        }

        /// <summary>
        /// 处理消息
        /// </summary>
        /// <param name="session"></param>
        /// <param name="requestInfo"></param>
        public static void ProcessMessage(LunarSession session, LunarRequestInfo requestInfo)
        {
            EProtocolId id = (EProtocolId)requestInfo.ProtocolID;

            if (!CheckProtocolId(session, requestInfo, id))
            {
                return;
            }

            //设置正在处理
            ThisPId = id;
            ThisSession = session;
            ThisReq = requestInfo;
            if (DictProtocolEvent.TryGetValue(id, out var action))
            {
                //处理
                try
                {
                    var StopwatchProcess = Stopwatch.StartNew();

                    action();

                    StopwatchProcess.Stop();
                    var UseMs = StopwatchProcess.ElapsedMilliseconds;
                    if (UseMs > 500)
                    {
                        loger.Error($"__________消息处理超时，消息:{id} 玩家ID:{ThisSession.Puid} 耗时:{UseMs} Ms__________");
                    }
                }
                catch (Exception e)
                {
                    loger.Fatal($"处理协议->  {id} -> {(int)id}出错 玩家ID:{ThisSession.Puid}", e);
                    session.Result(EProtocolResult.失败);
                    return;
                }
            }
            else
            {
                if (!BaseServerInfo.ServerRunModeIs外网)
                {
                    loger.Fatal($"处理协议->  {id} -> {(int)id} 未注册");
                    session.Result(EProtocolResult.失败);
                }
                return;
            }
        }
        //检查协议ID
        public static bool CheckProtocolId(LunarSession session, LunarRequestInfo requestInfo, EProtocolId id)
        {
            loger.Info($"处理协议-> {id} -> {(int)id} 。");
            if (loger.临时调试开关)
            {
                loger.DDD(requestInfo.Body);
            }

            //游戏服务器检查链接状态
            if (BaseServerInfo.ServerType == EServerType.游戏)
            {
                //检测是否登录
                if (!session.Loginded)
                {
                    if (id == EProtocolId.C2G_BASE_PING

                        || id == EProtocolId.C2L_LOGIN_NOTICESYSTEM
                        || id == EProtocolId.C2L_LOGIN_NOTICEACTIVITY

                        || id == EProtocolId.C2L_LOGIN_USERLOGIN

                        || id == EProtocolId.C2G_LOGIN_PLAYERLOGIN
                        || id == EProtocolId.C2G_LOGIN_PLAYERCREATE
                        || id == EProtocolId.C2G_LOGIN_PUIDLOGIN

                        || id == EProtocolId.C2G_NOTICE_SYSTEM
                        || id == EProtocolId.C2G_NOTICE_ACTIVITY

                        || id == EProtocolId.B2G_GT_ACTION
                        )
                    {

                    }
                    else
                    {
                        loger.Warn($"未登陆收到非登陆协议->  {id} -> {(int)id} 。");
                        return false;
                    }
                }
                else
                {
                    if ((id > EProtocolId.B2T_GT_START && id < EProtocolId.B2T_GT_END))
                    {

                    }
                    else
                    {
                        if (id == EProtocolId.C2G_LOGIN_PLAYERLOGIN 
                            || id == EProtocolId.C2G_LOGIN_PLAYERCREATE
                            || id == EProtocolId.C2G_LOGIN_PUIDLOGIN)
                        {
                            loger.Warn($"已登陆收到登陆协议-> {id} -> {(int)id} 。");
                            return false;
                        }
                        if (session.SessionObj == null)
                        {
                            loger.Warn($"已登陆收到未绑定玩家对象的协议-> {id} -> {(int)id} 。");
                            return false;
                        }
                    }
                }
            }
            return true;
        }

        #region 发送消息
        // 发送消息(通过session)
        public static short Send<T>(T objMsg) where T : ProtocolMsgBase
        {
            ThisSession.Send(objMsg);
            return 0;
        }
        // 广播给所有连接
        public static void SendAllSessions<T>(T objMsg) where T : ProtocolMsgBase
        {
            foreach (var session in BaseAppServer.AllSessions.Values)
            {
                session.Send(objMsg);
            }
        }
        // 返回通用错误
        public static void Result(this LunarSession session, EProtocolResult result = EProtocolResult.失败)
        {
            var objMsg = new G2C_Base_Result()
            {
                HandleId = (int)ThisPId,
                Result = result,
            };
            Send(objMsg);
        }
        #endregion




        


    }

}